const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

// 配置 multer 的磁盘存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 指定文件存储的目录
        const uploadDir = path.join(__dirname, '../../uploadFiles');
        // 检查目录是否存在，如果不存在则创建
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        // 为文件生成唯一的名称
        const uniqueSuffix = uuidv4();
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage }).single('file');

exports.uploadFile = (req, res, next) => {
    upload(req, res, (err) => {
        if (err) {
            // 处理 multer 抛出的错误
            return res.status(400).send({ message: 'Error uploading file: ' + err.message });
        }
        if (!req.file) {
            // 如果没有文件上传，返回错误信息
            return res.status(400).send({ message: 'No file uploaded.' });
        }
        // 文件上传成功的处理
        res.json({
            code: 200,
            message: "上传成功",
            data: {
                fileUrl: `http://localhost:3000/uploadFiles/${req.file.filename}`,
                fileType: req.file.mimetype,
            }
        })
    });
};